package com.example.gitclient.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.gitclient.R;
import com.example.gitclient.model.Branch;

import java.util.List;

/**
 * 分支列表适配器
 */
public class BranchAdapter extends RecyclerView.Adapter<BranchAdapter.ViewHolder> {
    private final List<Branch> branches;
    private final OnBranchClickListener listener;

    /**
     * 分支点击监听器接口
     */
    public interface OnBranchClickListener {
        void onBranchClick(Branch branch);
    }

    /**
     * 创建分支列表适配器
     * @param branches 分支列表
     * @param listener 点击监听器
     */
    public BranchAdapter(List<Branch> branches, OnBranchClickListener listener) {
        this.branches = branches;
        this.listener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_branch, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Branch branch = branches.get(position);
        
        // 设置分支名称
        holder.tvBranchName.setText(branch.getDisplayName());
        
        // 设置最后提交信息
        if (branch.getLastCommitMessage() != null && !branch.getLastCommitMessage().isEmpty()) {
            holder.tvLastCommit.setText(branch.getLastCommitMessage());
            holder.tvLastCommit.setVisibility(View.VISIBLE);
        } else {
            holder.tvLastCommit.setVisibility(View.GONE);
        }
        
        // 如果是当前分支，显示标记
        if (branch.isCurrent()) {
            holder.tvCurrentIndicator.setVisibility(View.VISIBLE);
        } else {
            holder.tvCurrentIndicator.setVisibility(View.GONE);
        }

        // 设置点击事件
        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onBranchClick(branch);
            }
        });
    }

    @Override
    public int getItemCount() {
        return branches.size();
    }

    /**
     * 视图持有者
     */
    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvBranchName;
        TextView tvLastCommit;
        TextView tvCurrentIndicator;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvBranchName = itemView.findViewById(R.id.tvBranchName);
            tvLastCommit = itemView.findViewById(R.id.tvLastCommit);
            tvCurrentIndicator = itemView.findViewById(R.id.tvCurrentIndicator);
        }
    }
}